# -*- coding: UTF-8 -*-
"""
@描述：数据库连接池管理模块
"""

import pymysql
from DBUtils.PooledDB import PooledDB
import config.setting as setting

pool_dict = dict()


def get_connection(host, port, user, password):
    if host in pool_dict:
        return pool_dict.get(host).get_conn()
    else:
        pool = ConnectionPool(host, port, user, password)
        pool_dict.setdefault(host, pool)
        return pool.get_conn()


class ConnectionPool(object):
    __pool = None

    def __init__(self, host, port, user, password):
        if self.__pool is None:
            self.__pool = PooledDB(creator=pymysql, mincached=setting.DB_MIN_CACHED, maxcached=setting.DB_MAX_CACHED,
                                   maxshared=setting.DB_MAX_SHARED, maxconnections=setting.DB_MAX_CONNECYIONS,
                                   blocking=setting.DB_BLOCKING, maxusage=setting.DB_MAX_USAGE,
                                   setsession=setting.DB_SET_SESSION,
                                   host=host, port=port,
                                   user=user, passwd=password, use_unicode=False,
                                   charset=setting.DB_CHARSET)

    def get_conn(self):
        return self.__pool.connection()


if __name__ == '__main__':
    insert_columns = ['id', 'name']
    conn = get_connection(setting.DB_HOST, setting.DB_PORT, setting.DB_USER, setting.DB_PASSWORD)
    cursor = conn.cursor()
    sql = 'replace into dbinfoflow.testtable ({cloumns}) values (%s, %s)'.format(cloumns=','.join(insert_columns))
    item = [77, '王杰'.encode()]
    item1 = [66, '王杰']
    print(item)
    print(sql)
    cursor.executemany(sql, [item, item1])
    conn.commit()
    cursor.close()
    conn.close()
